#ifndef UNIT_H
#define UNIT_H

#include "../utils/map.h"
typedef enum{
    UNIT_SERVICE=1, // service unit
    UNIT_TARGET,    // target unit
    UNIT_SOCKET,    // socket unit
    UNIT_MOUNT,     // mount unit
} UnitType;

typedef enum{
    UNIT_INACTIVE,
    UNIT_INACTIVATING,
    UNIT_ACTIVE,
    UNIT_FAILED,
    UNIT_UNKNOWN,
} UnitState;

// 定义unit结构体
typedef struct Unit {
    char*       name;
    char*       dir;
    UnitType    type;
    UnitState   state;
    // 依赖关系
    char**      requires;
    int         requires_size;
    HashMap*    dependencies; // 正向依赖关系:after, wants, requires
    HashMap*    reverse_deps; // 反向依赖关系:before
    // 依赖关系计数
    int         in_degree;
    int         out_degree;
    int         ref_count;
    // 任务队列
    struct Unit **taskQueue;
    size_t      taskQueueSize;
    // 时间戳
    long        m_time;
}Unit;

/*
* 定义service unit结构体
*/
typedef struct 
{
    // 基本信息
    Unit        meta;
    // [Unit]段落
    char*       description;
    char*       install;
    char**      afterbyname;
    char**      beforebyname;
    char**      wantsbyname;
    char**      requires;
    long        m_time;
    // [Service]段落
    char*       binpath;
    char*       binname;
    char**      argv;
    char**      environ;
    char*       std_in;
    char*       std_out;
    char*       std_err;
    int         start_timeout;
    int         start_retries;
    int         start_interval;
    int         start_type;
    int         restart_count;
    int         pid;
    // [Install]段落
    char*       wanted_by;
    char*       required_by;
}Service;
/*
* 定义target unit结构体
*/
typedef struct 
{
    Unit        meta;
    // [Unit]段落
    char*       description;
    char*       install;
    char**      afterbyname;
    char**      beforebyname;
    char**      wantsbyname;
    char**      requires;
    long        m_time;
    // [Target]段落
    char*       name;
    int         unit_num;  
    void*       unit;
    // 依赖关系
}Target;

// 事务类型
typedef enum {
    TRANSACTION_COMPLETE,
    TRANSACTION_WAIT,
    TRANSACTION_START,
    TRANSACTION_STOP,
    TRANSACTION_RESTART,
    TRANSACTION_RELOAD,
    TRANSACTION_ERROR
} TransactionState;

typedef struct Transaction {
    TransactionState    state;
    Unit*               obj; // 事务对象unit: 需要执行的service, target, socket, mount
    int count;
    int index;
    int error;
} Transaction;


// 定义unit数组结构体
typedef struct{
    unsigned int size;     // 数组大小
    unsigned int capacity; // 数组容量
    Unit *units;    // 数组指针
} UnitArray;
// 定义unit操作函数
Unit * unitLoadFrom(const char *path);
int unitHasName(const Unit *unit, const char *name);

//TransactionState driveTranstion(Transaction *trans);
// 定义unit数组操作函数
int unitArrayInit(UnitArray * unitarry,unsigned int size);
int unitArrayAdd(UnitArray * unitarry, Unit *unit);
int unitArrayUpdate(UnitArray * unitarry, int index, Unit *unit);
int unitArrayGet(UnitArray * unitarry, int index, Unit *unit);
// int unitArrayFree(UnitArray * unitarry);

#endif
